package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.IncludeOtherException;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.mappper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>  implements CategoryService {

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    @Override
    public void deleteById(Long id) {

        //判断该分类是否还包含菜品（计数所含菜品总数）
        LambdaQueryWrapper<Dish> dishWrapper = new LambdaQueryWrapper<>();
        dishWrapper.eq(Dish::getCategoryId, id);
        int dishCount = dishService.count(dishWrapper);

        //大于0，说明此时该分类下包含其他菜品 抛出自定义异常
        if (dishCount > 0) {
            throw new IncludeOtherException("该分类下包含菜品，请先删除该分类下所有菜品再删除");
        }

        //判断该分类是否还包含套餐（计数所含套餐总数）
        LambdaQueryWrapper<Setmeal> setmealWrapper = new LambdaQueryWrapper<>();
        setmealWrapper.eq(Setmeal::getCategoryId, id);
        int setmealCount = setmealService.count(setmealWrapper);

        //大于0，说明此时该分类下包含其他套餐 抛出自定义异常
        if (setmealCount > 0) {
            throw new IncludeOtherException("该分类下包含套餐，请先删除该分类下所有菜品再删除");
        }

        this.removeById(id);
    }
}